import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
import '../models/folder_model.dart';
import 'draggable_folder_item.dart';

/**
 * 文件夹树视图组件
 * 提供完整的层级关系显示和管理功能
 */
class FolderTreeView extends StatefulWidget {
  final List<FolderModel> folders;
  final String? selectedFolderId;
  final Function(FolderModel) onFolderSelected;
  final Function(FolderModel, FolderModel) onFolderMoved;
  final Function(FolderModel) onFolderExpansionChanged;
  final Function(FolderModel)? onFolderEdit;
  final Function(FolderModel)? onFolderDelete;
  final Function()? onAddFolder;

  const FolderTreeView({
    super.key,
    required this.folders,
    this.selectedFolderId,
    required this.onFolderSelected,
    required this.onFolderMoved,
    required this.onFolderExpansionChanged,
    this.onFolderEdit,
    this.onFolderDelete,
    this.onAddFolder,
  });

  @override
  State<FolderTreeView> createState() => _FolderTreeViewState();
}

class _FolderTreeViewState extends State<FolderTreeView> {
  /**
   * 构建文件夹树
   */
  List<Widget> _buildFolderTree() {
    final rootFolders = widget.folders
        .where((folder) => folder.parentId == null)
        .toList()
      ..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
    
    final List<Widget> widgets = [];
    
    for (final folder in rootFolders) {
      widgets.addAll(_buildFolderWithChildren(folder, 0));
    }
    
    return widgets;
  }

  /**
   * 递归构建文件夹及其子文件夹
   */
  List<Widget> _buildFolderWithChildren(FolderModel folder, int depth) {
    final List<Widget> widgets = [];
    
    // 添加当前文件夹
    widgets.add(
      DraggableFolderItem(
        folder: folder,
        isSelected: widget.selectedFolderId == folder.id,
        depth: depth,
        onTap: widget.onFolderSelected,
        onDrop: widget.onFolderMoved,
        onExpansionChanged: widget.onFolderExpansionChanged,
        onEdit: () => widget.onFolderEdit?.call(folder),
        onDelete: () => widget.onFolderDelete?.call(folder),
      ),
    );
    
    // 如果文件夹展开，添加子文件夹
    if (folder.isExpanded && folder.childrenIds.isNotEmpty) {
      final children = widget.folders
          .where((f) => folder.childrenIds.contains(f.id))
          .toList()
        ..sort((a, b) => a.sortOrder.compareTo(b.sortOrder));
      
      for (final child in children) {
        widgets.addAll(_buildFolderWithChildren(child, depth + 1));
      }
    }
    
    return widgets;
  }

  /**
   * 构建添加文件夹按钮
   */
  Widget _buildAddFolderButton() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: ListTile(
        leading: Icon(
          Icons.add,
          size: 20,
          color: AppTheme.primaryColor,
        ),
        title: Text(
          '新建文件夹',
          style: TextStyle(
            fontSize: 14,
            color: AppTheme.primaryColor,
            fontWeight: FontWeight.w500,
          ),
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        onTap: widget.onAddFolder,
      ),
    );
  }

  /**
   * 构建空状态
   */
  Widget _buildEmptyState() {
    return Container(
      padding: const EdgeInsets.all(24),
      child: Column(
        children: [
          Icon(
            Icons.folder_outlined,
            size: 48,
            color: AppTheme.textSecondary,
          ),
          const SizedBox(height: 16),
          Text(
            '暂无文件夹',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
              color: AppTheme.textSecondary,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '创建您的第一个文件夹来组织笔记',
            style: TextStyle(
              fontSize: 14,
              color: AppTheme.textSecondary,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          ElevatedButton.icon(
            onPressed: widget.onAddFolder,
            icon: const Icon(Icons.add),
            label: const Text('新建文件夹'),
            style: ElevatedButton.styleFrom(
              backgroundColor: AppTheme.primaryColor,
              foregroundColor: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /**
   * 构建文件夹统计信息
   */
  Widget _buildFolderStats() {
    final totalFolders = widget.folders.length;
    final rootFolders = widget.folders.where((f) => f.parentId == null).length;
    
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppTheme.sidebarSelected,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(
            Icons.folder,
            size: 16,
            color: AppTheme.textSecondary,
          ),
          const SizedBox(width: 8),
          Text(
            '共 $totalFolders 个文件夹，$rootFolders 个根目录',
            style: TextStyle(
              fontSize: 12,
              color: AppTheme.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题和统计
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '我的文件夹',
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: AppTheme.textSecondary,
                ),
              ),
              if (widget.onAddFolder != null)
                GestureDetector(
                  onTap: widget.onAddFolder,
                  child: Icon(
                    Icons.add,
                    size: 16,
                    color: AppTheme.primaryColor,
                  ),
                ),
            ],
          ),
        ),
        
        // 文件夹统计信息
        if (widget.folders.isNotEmpty) _buildFolderStats(),
        
        // 文件夹列表或空状态
        if (widget.folders.isEmpty)
          _buildEmptyState()
        else ...[
          ..._buildFolderTree(),
          if (widget.onAddFolder != null) _buildAddFolderButton(),
        ],
      ],
    );
  }
}